import {createRouter, createWebHashHistory} from 'vue-router'
import store from '../store/index.js'
import {getLoginerInfo, getUserById} from "../service/userApi.js";
// ********************** 公共路由（无需认证） **************************
const publicRoutes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('../views/Login.vue'),
        meta: {
            title: '用户登录',
            layout: 'auth'
        }
    },
    {
        path: '/register',
        name: 'Register',
        component: () => import('../views/Register.vue'),
        meta: {
            title: '用户注册',
            layout: 'auth'
        }
    },
    {
        path: '/agreement',
        name: 'Agreement',
        component: () => import('../views/client/Agreement.vue'),
        meta: {
            title: '用户服务协议',
            layout: 'auth'
        }
    },
    {
        path: '/privacyPolicy',
        name: 'PrivacyPolicy',
        component: () => import('../views/client/PrivacyPolicy.vue'),
        meta: {
            title: '隐私政策',
            layout: 'auth'
        }
    },

    {
        path: '/loading',
        name: 'Loading',
        component: () => import('../views/Loading.vue'),
        meta: {
            title: '加载中',
            layout: 'auth'
        }
    },
    {
        path: '/resetPassword',
        name: 'ResetPassword',
        component: () => import('../views/ForgetPassword.vue'),
        meta: {
            title: '忘记密码',
            layout: 'auth'
        }
    }
]

// ********************** 管理员路由（需要认证） **************************
const adminRoutes = [
    {
        path: '/system/homePage',
        name: 'systemHomePage',
        component: () => import('../views/admin/HomePage.vue'),
        meta: {
            title: '系统首页',
            requiresAuth: true,
            layout: 'admin'
        }
    },
    {
        path: '/video/info',
        name: 'videoInfo',
        component: () => import('../views/admin/Video.vue'),
        meta: {
            title: '视频管理',
            requiresAuth: true,
            layout: 'admin'
        }
    },
    {
        path: '/information/classify',
        name: 'informationClassify',
        component: () => import('../views/admin/InformationClassify.vue'),
        meta: {
            title: '资讯分类管理',
            requiresAuth: true,
            layout: 'admin'
        }
    },
    {
        path: '/information/info',
        name: 'informationInfo',
        component: () => import('../views/admin/InformationInfo.vue'),
        meta: {
            title: '资讯信息管理',
            requiresAuth: true,
            layout: 'admin'
        }
    },
    {
        path: '/activity/public',
        name: 'activityPublic',
        component: () => import('../views/admin/ActivityPublic.vue'),
        meta: {
            title: '公益活动发布',
            requiresAuth: true,
            layout: 'admin'
        }
    },
    {
        path: '/activity/register',
        name: 'activityRegister',
        component: () => import('../views/admin/ActivityRegister.vue'),
        meta: {
            title: '活动报名管理',
            requiresAuth: true,
            layout: 'admin'
        }
    },
    {
        path: '/service/pension',
        name: 'servicePension',
        component: () => import('../views/admin/ServicePension.vue'),
        meta: {
            title: '养老服务管理',
            requiresAuth: true,
            layout: 'admin'
        }
    },
    {
        path: '/service/appointment',
        name: 'serviceAppointment',
        component: () => import('../views/admin/ServiceAppointment.vue'),
        meta: {
            title: '服务预约管理',
            requiresAuth: true,
            layout: 'admin'
        }
    },
    {
        path: '/nursing/home',
        name: 'nursingHome',
        component: () => import('../views/admin/NursingHome.vue'),
        meta: {
            title: '养老院信息维护',
            requiresAuth: true,
            layout: 'admin'
        }
    },
    {
        path: '/comment/info',
        name: 'commentInfo',
        component: () => import('../views/admin/CommentInfo.vue'),
        meta: {
            title: '用户评论审核',
            requiresAuth: true,
            layout: 'admin'
        }
    },
    {
        path: '/announcement/info',
        name: 'announcementInfo',
        component: () => import('../views/admin/AnnouncementInfo.vue'),
        meta: {
            title: '公告信息发布',
            requiresAuth: true,
            layout: 'admin'
        }
    },
    {
        path: '/user/info',
        name: 'userInfo',
        component: () => import('../views/admin/UserInfo.vue'),
        meta: {
            title: '用户信息管理',
            requiresAuth: true,
            layout: 'admin'
        }
    },
    {
        path: '/user/updatePwd',
        name: 'userUpdatePwd',
        component: () => import('../views/admin/UserUpdatePwd.vue'),
        meta: {
            title: '修改管理员密码',
            requiresAuth: true,
            layout: 'admin'
        }
    }
]

// ********************** 客户端路由（需要认证） **************************
const clientRoutes = [
    // 客户端首页
    {
        path: '/client/home',
        name: 'clientHome',
        component: () => import('../views/client/Index.vue'),
        meta: {
            title: '首页',
            requiresAuth: true,
            layout: 'client'
        }
    },
    // 公益活动列表页面
    {
        path: '/client/activityList',
        name: 'clientActivityList',
        component: () => import('../views/client/ActivityList.vue'),
        meta: {
            title: '公益活动列表',
            requiresAuth: true,
            layout: 'client'
        }
    },
    // 养老服务列表页面
    {
        path: '/client/serviceList',
        name: 'clientServiceList',
        component: () => import('../views/client/ServiceList.vue'),
        meta: {
            title: '养老服务列表',
            requiresAuth: true,
            layout: 'client'
        }
    },
    // 养老院信息列表页面
    {
        path: '/client/nursingList',
        name: 'clientNursingList',
        component: () => import('../views/client/NursingList.vue'),
        meta: {
            title: '养老院信息列表',
            requiresAuth: true,
            layout: 'client'
        }
    },
    {
        path: '/client/chat',
        name: 'chatWindow',
        component: () => import('../views/client/ChatWindow.vue'),
        meta: {
            title: 'AI智能对话',
            requiresAuth: true,
            layout: 'client'
        }
    },
    {
        path: '/client/videoStudy',
        name: 'clientVideoStudy',
        component: () => import('../views/client/VideoStudy.vue'),
        meta: {
            title: '视频学习',
            requiresAuth: true,
            layout: 'client'
        }
    },
    // 首页用户信息编辑
    {
        path: '/userInfo/editMessage',
        name: 'userInfoEdit',
        component: () => import('../views/client/EditMessage.vue'),
        meta: {
            title: '首页用户信息编辑',
            requiresAuth: true,
            layout: 'client'
        }
    },
    // 我报名的活动的页面
    {
        path: '/register/Activity',
        name: 'RegisterActivity',
        component: () => import('../views/client/MyActivity.vue'),
        meta: {
            title: '报名活动页面',
            requiresAuth: true,
            layout: 'client'
        }
    },
    // 我的预约服务页面
    {
        path: '/appo/Service',
        name: 'AppoService',
        component: () => import('../views/client/MyService.vue'),
        meta: {
            title: '预约服务页面',
            requiresAuth: true,
            layout: 'client'
        }
    },
    //老人管理
    {
        path: '/manager/Elderly',
        name: 'ManagerElderly',
        component: () => import('../views/client/MyElderly.vue'),
        meta: {
            title: '老人管理页面',
            requiresAuth: true,
            layout: 'client'
        }
    },
    // 资讯信息详情页面
    {
        path: '/client/infoDetail/:id',
        name: 'clientInfoNewsDetail',
        component: () => import('../views/client/InfoDetail.vue'),
        meta: {
            title: '资讯信息详情页面',
            requiresAuth: true,
            layout: 'client'
        }
    },
    //公益服务详情页面
    {
        path: '/client/activity/:id',
        name: 'clientActivityDetail',
        component: () => import('../views/client/ActivityDetail.vue'),
        meta: {
            title: '公益活动详情',
            requiresAuth: true,
            layout: 'client',
        }
    },
    //学习视频详情页面
    {
        path: '/client/videoDetail/:id',
        name: 'clientVideoDetail',
        component: () => import('../views/client/VideoDetail.vue'),
        meta: {
            title: '学习视频详情',
            requiresAuth: true,
            layout: 'client',
        }
    },
    // 其他客户端页面...

];

const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        ...publicRoutes,
        {
            path: '/',
            redirect: () => {
                const isAuthenticated = store.getters.isAuthenticated;
                if (isAuthenticated) {
                    return store.getters.isAdmin ? '/system/homePage' : '/client/home';
                } else {
                    return '/login';
                }
            }
        },
        {
            path: '/system',
            redirect: '/system/homePage' // 后台管理端默认重定向到首页
        },
        {
            path: '/client',
            redirect: '/client/home' // 客户端默认重定向到首页
        },
        ...adminRoutes,
        ...clientRoutes
    ]
});

// 路由守卫
router.beforeEach(async (to, from, next) => {
    try {
        // 如果已登录但角色未初始化，尝试从接口获取用户信息
        if (store.getters.isAuthenticated && !store.getters.isAdmin && !store.getters.isClient) {
            try {
                const res = await getLoginerInfo(); // 你的用户信息接口
                const role = res.data.role === '管理员' ? 'admin' : 'client';
                if (role === 'admin') {
                    store.commit('setAdminRole');
                } else {
                    store.commit('setClientRole');
                }
            } catch (error) {
                console.error('获取用户信息失败', error);
                store.commit('clearToken');
                return next('/login');
            }
        }

        const isAuthenticated = store.getters.isAuthenticated;
        const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
        const isPublic = to.meta.layout === 'auth' || to.path === '/login' || to.path === '/register';
        // 已登录访问认证页
        if (isAuthenticated && isPublic) {
            let targetPath = '/';
            if (store.getters.isClient) {
                targetPath = '/client/home';
            } else if (store.getters.isAdmin) {
                targetPath = '/system/homePage';
            }
            return next(targetPath);
        }

        // 需要认证且未登录
        if (requiresAuth && !isAuthenticated) {
            if (!/^\/\w+/.test(to.fullPath)) {
                return next('/login');
            }
            return next(`/login?redirect=${encodeURIComponent(to.fullPath)}`);
        }

        next();
    } catch (error) {
        console.error('路由守卫错误:', error);
        next('/error'); // 跳转到错误页面
    }
});
export default router